package rhc.spider.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SingleInstanceUtil {

	private static final Map<Class,Object> SINGLE_INSTANCE=new ConcurrentHashMap<Class,Object>();
	
	private static final Logger logger=Logger.getLogger(SingleInstanceUtil.class.getName());
	
	/**获取单例
	 * @param _class
	 * @return
	 */
	public static <T> T getInstance(Class<T> _class){
		
		if(!SINGLE_INSTANCE.containsKey(_class)){
			createInstance(_class);
		}
		
		return (T) SINGLE_INSTANCE.get(_class);
	}
	
	/**注册一个单例
	 * @param _class
	 * @param t
	 */
	public static <T> void registerInstance(Class<T> _class,T t){
		SINGLE_INSTANCE.put(_class, t);
	}
	
	/**创建单例
	 * @param _class
	 */
	private synchronized static <T> void createInstance(Class<T> _class){
		
		if(SINGLE_INSTANCE.containsKey(_class)){
			return;
		}
		
		try {
			Object instance = _class.newInstance();
			SINGLE_INSTANCE.put(_class, instance);
		} catch (Exception e) {
			logger.log(Level.INFO, _class.getName()+" 初始化出错");
			e.printStackTrace();
		}
	}
}
